<template>
  <PageContainer>
    <Header title="高级设置" />
    <view
      style="
        background: 'linear-gradient(156deg, rgba(255, 242, 142, 0.20) 0%, rgba(255, 234, 201, 0.00) 61.79%), linear-gradient(180deg, #DFEBFF 0%, rgba(227, 238, 255, 0.00) 100%), #FFF';
      "
      class="hb-p-4"
    >
      <tm-form
        @submit="handleSubmit"
        layout="vertical"
        :model-value="formData"
        :margin="[0, 0]"
        :padding="[0, 0]"
        :border="false"
        :label-align="'top'"
        :transparent="true"
      >
        <view class="hb-flex hb-flex-col hb-gap-4">
          <view class="hb-text-sm hb-text-[#969799]">基础资料</view>
          <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-xl">
            <tm-form-item
              required
              field="iconFileUrl"
              label="智能助手头像"
              :border="false"
              :margin="[0, 0]"
              :rules="[{ required: true, message: '请上传智能助手头像' }]"
            >
              <view class="hb-flex hb-items-center hb-gap-4 hb-flex-col hb-justify-center">
                <TImage
                  :src="formData.iconFileUrl"
                  width="160rpx"
                  height="160rpx"
                  border-radius="16rpx"
                  error-img-type="person"
                />
                <text
                  class="hb-text-sm hb-text-[#2878FF] hb-py-1 hb-px-2 hb-inline-block hb-rounded-full hb-border hb-border-[#2878FF]"
                  @click="handleUploadAvatar"
                >
                  更换
                </text>
              </view>
            </tm-form-item>
          </view>
          <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-xl">
            <tm-form-item
              required
              field="name"
              label="智能助手名称"
              :border="false"
              :margin="[0, 0]"
              :rules="[{ required: true, message: '请输入智能助手名称' }]"
            >
              <TmInput
                v-model="formData.name"
                :height="88"
                :font-size="28"
                placeholder="请输入智能助手名称"
                :maxlength="20"
              />
            </tm-form-item>
          </view>

          <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-xl">
            <tm-form-item field="description" label="智能助手简介" :border="false" :margin="[0, 0]">
              <TmInput
                v-model="formData.description"
                :height="160"
                :font-size="28"
                :input-padding="[16]"
                placeholder="一句话介绍你的智能助手"
                type="textarea"
              />
            </tm-form-item>
          </view>
          <view class="hb-text-sm hb-text-[#969799]">对话设置</view>
          <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-xl">
            <tm-form-item field="prologue" :border="false" :margin="[0, 0]">
              <template #label>
                <view class="hb-flex hb-items-center hb-gap-2">
                  <text class="hb-text-sm">开场白</text>
                  <text
                    class="hb-text-xs hb-text-[#2878FF]"
                    @click="handleUploadBackground('kaiChangBai.png')"
                  >
                    查看示例
                  </text>
                </view>
              </template>
              <view class="hb-my-2 hb-text-xs hb-text-[#969799]">
                将在用户开启对话时展示，引导用户快速开启对话。
              </view>
              <TmInput
                v-model="formData.prologue"
                :height="160"
                :font-size="28"
                :input-padding="[16]"
                placeholder="Hi~我是深圳市高州商会的智能助手，请问有什么可以帮到您?"
                type="textarea"
              />
            </tm-form-item>
          </view>

          <view
            v-if="formData.suggestedQuestions?.length"
            class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-xl"
          >
            <tm-form-item field="suggestedQuestions" :border="false" :margin="[0, 0]">
              <template #label>
                <view class="hb-flex hb-items-center hb-gap-2">
                  <text class="hb-text-sm">开场白预置问题</text>
                  <text
                    class="hb-text-xs hb-text-[#2878FF]"
                    @click="handleUploadBackground('kaiChangBaiWenTi.png')"
                  >
                    查看示例
                  </text>
                </view>
              </template>

              <view class="hb-flex hb-flex-col hb-gap-2 hb-mt-2">
                <TmInput
                  v-for="(item, index) in formData.suggestedQuestions"
                  :key="index"
                  v-model="formData.suggestedQuestions[index]"
                  :height="88"
                  :font-size="28"
                  placeholder="请输入预置问题"
                  :maxlength="20"
                >
                  <template #right>
                    <tm-icon
                      v-if="formData.suggestedQuestions.length > 1"
                      name="ali-icon icon-delete"
                      :font-size="44"
                      color="#969799"
                      :padding="[8]"
                      @click="handleDelete(index)"
                    />
                  </template>
                </TmInput>
              </view>
              <tm-button
                v-if="formData.suggestedQuestions.length < 3"
                :width="250"
                :height="48"
                :round="10"
                :follow-theme="false"
                color="#D0F7FF"
                font-color="#2878FF"
                @click="handleAdd"
                :label="`增加问题(${formData.suggestedQuestions.length}/3)`"
                icon="ali-icon icon-jiahao1"
              ></tm-button>
            </tm-form-item>
          </view>

          <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-xl">
            <tm-form-item field="backImage" :border="false" :margin="[0, 0]">
              <template #label>
                <view class="hb-flex hb-items-center hb-gap-2">
                  <text class="hb-text-sm">聊天背景</text>
                  <text
                    class="hb-text-xs hb-text-[#2878FF]"
                    @click="handleUploadBackground('liaoTian.png')"
                  >
                    查看示例
                  </text>
                </view>
              </template>
              <view class="hb-my-3 hb-text-xs hb-text-[#969799]">建议上传尺寸：750*1200px</view>
              <ImgUpload
                v-model="backImage"
                :image-height="backImage.length ? 1200 : 180"
                :row="1"
                :border-radius="8"
                :image-width="622"
                :width="622"
              />
            </tm-form-item>
          </view>
        </view>
        <BottomSubmit :submit-btn-label="`保存并发布`" :submitLoading="loading" />
      </tm-form>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* aiAdvancedSettings 高级设置 */
  import { botAddOrUpdate, getBotAdvancedSettings } from '@/api/aiSettings';
  import { AiAddOrUpdateData } from '@/api/aiSettings/types';
  import { TabbarPageEnum } from '@/enums/PageEnum';
  import { useUpload } from '@/hooks/file/useUpload';
  import { useUserStore } from '@/store/modules/user';
  const userStore = useUserStore();
  const formData = reactive<AiAddOrUpdateData>({} as AiAddOrUpdateData);
  const backImage = ref<string[]>([]);
  onMounted(async () => {
    const res = await getBotAdvancedSettings();
    formData.prompt = res.prompt;
    formData.name = res.name;
    formData.description = res.description;
    formData.iconFileUrl = res.iconFileUrl;
    formData.prologue = res.prologue;
    formData.backImage = res.backImage;
    formData.suggestedQuestions = res.suggestedQuestions || [''];
    formData.id = res.id;
    backImage.value = res.backImage ? [res.backImage] : [];
  });
  const handleDelete = (index: number) => {
    formData.suggestedQuestions.splice(index, 1);
  };

  const handleAdd = () => {
    formData.suggestedQuestions.push('');
  };
  const { chooseFile, successResult, delResultItem } = useUpload();
  const handleUploadAvatar = () => {
    chooseFile({
      mediaType: 'image',
    });
  };
  watch(
    () => successResult,
    (res) => {
      if (res.value[0]) {
        formData.iconFileUrl = res.value[0].filePath!;
        nextTick(() => {
          delResultItem(0);
        });
      }
    },
    {
      deep: true,
    },
  );

  const loading = ref(false);
  const handleSubmit = async (e: Tmui.tmFormSubmitResult<typeof formData>) => {
    try {
      // 表单验证
      if (!e.isPass) return;
      // 防止重复提交
      if (loading.value) return;
      loading.value = true;
      formData.backImage = backImage.value[0] || '';
      formData.suggestedQuestions = formData.suggestedQuestions.filter((item) => item);
      await botAddOrUpdate(formData);
      userStore.getUserInfo();
      uni.showModal({
        title: '发布成功',
        content: '您的智能助手设置已保存，是否要继续去完善知识库？',
        cancelColor: '#969799',
        cancelText: '回到首页',
        confirmColor: '#2878FF',
        confirmText: '立即完善',
        success: (res) => {
          if (res.confirm) {
            navigateTo({
              name: 'knowledgeBase',
            });
          } else {
            switchTab(TabbarPageEnum.BASE_HOME);
          }
        },
      });
    } catch (e) {
      console.error('表单验证失败', e);
    } finally {
      loading.value = false;
    }
  };
  const handleUploadBackground = (imgName: string) => {
    console.log('imgName', imgName);
    uni.previewImage({
      urls: [`https://hb-saas.obs.cn-south-1.myhuaweicloud.com/saas-ai/${imgName}`],
      success: (res) => {
        console.log('res', res);
      },
      fail: (err) => {
        console.log('err', err);
      },
    });
  };
</script>

<style lang="scss" scoped></style>
